<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：Finance.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\admin;

use app\common\builder\ZBuilder;
use app\admin\controller\Admin;

class Order extends Admin
{

    /**
     * 运单登记列表
     * @author 
     */
    public function index()
    {

        $OrderModel = new OrderModel();
        $map = $this->getMap();
        $order = $this->getOrder();
        $data_list = $OrderModel->get_data($map, $order);
        return ZBuilder::make('table')
            ->setPageTitle('托运单登记列表')// 设置页面标题
            ->setTableName('logistics_order')// 设置数据表名
            ->addOrder('id')
            ->hideCheckbox()
            ->setSearch(['code'])// 设置搜索参数
            ->addFilter('state', OrderModel::$state)// 添加筛选
            ->addFilter(['username' => 'logistics_user.name'])// 添加筛选
            ->addFilter(['name' => 'logistics_companyuser.name'])// 添加筛选
            ->addFilter('logistics_order.is_money', ['否', '是'])// 添加时间段筛选
            ->addTimeFilter('logistics_order.create_time')// 添加时间段筛选
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['nickname', '开单员'],
                ['code', '配送单号'],
                ['username', '跟车员'],
                ['start_name', '发货人姓名'],
                ['start_tel', '发货人手机号码'],
                ['receive_name', '收货人姓名'],
                ['receive_tel', '收货人手机号码'],
                ['start_store_name', '收货门店'],
                ['receive_store_name', '到货门店'],
                ['start_money', '货款'],
                ['receive_money', '运费'],
                ['state', '状态', 'select', OrderModel::$state],
                ['content', '备注'],
                ['create_time', '创建时间', 'datetime'],
                ['update_time', '最后更新时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add', [], true)
            ->addRightButton('edit', [], true)
            ->addRightButtons([
                'delete',
                'shouhuo' => ['title' => '收货单', 'icon' => 'fa fa-fw fa-indent', 'href' => url('shouhuo', ['id' => '__id__',])],
                'qianshou' => ['title' => '签收单', 'icon' => 'fa fa-fw fa-outdent', 'href' => url('qianshou', ['id' => '__id__',])],

            ])
            ->setRowList($data_list['content']['info'])// 设置表格数据
            ->fetch(); // 渲染页面
    }


    /**
     * 更改运单状态
     * @author 
     */
    public function quickEdit($record = [])
    {
        $data = input();
        $order = OrderModel::get($data['pk']);
        if ($data['name'] == 'state') {//订单状态
            if ($data['value'] != $order->state + 1) $this->error('违规的操作!');
            $username = get_nickname(is_signin());
            $OrderModel = new OrderModel();
            $data = $OrderModel->edit_status($data['pk'], $username, 'admin');
            if (!$data['status']) return $this->error($data['msg']);
        }
    }


    /**
     * 添加运单
     * @author 
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $data = input();
            $validate = $this->validate($data, 'Order');
            if ($validate !== true) $this->error($validate);
            $OrderModel = new OrderModel();
            $data['start_detailed'] = $OrderModel->get_goods($data['start_detailed']);
            $id = is_signin();
            $data['admin_id'] = $id;
            if ($info = OrderModel::create($data)) {
                $username = get_nickname($id);
                $storemodel = StoreModel::get($info->staer_store_id);
                $staer_name = $storemodel->name;
                //收货门店
                $receivemodel = StoreModel::get($info->receive_store_id);
                $receive_name = $receivemodel->name;
                $content = $staer_name . '门店发往' . $receive_name . '门店的订单已生成,操作员' . $username;
                $ordermainmodel = new OrderMain();
                $ordermainmodel->order_id = $info->id;
                $ordermainmodel->content = $content;
                $ordermainmodel->save();

                $this->success('新增成功', url('index'), '_parent_reload');
            } else {
                $this->error('操作失败', url('index'), '_parent_reload');
            }
        }


        $user_id = is_signin();
        $user = User::get($user_id);
        return ZBuilder::make('form')
            ->setPageTitle('新增托运单')// 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['select', 'start_id', '选择发货人*', '', CompanyuserModel::column('name', 'id')],
                // ['select', 'user_id', '请选择跟车员','',UserModel::where(['group_id'=>1,'status'=>1])->whereor('state','=','1,2')->column('name','id')],
                ['linkage', 'staer_branch_id', '选择发货网点*', '', BranchModel::where(['status' => 1])->column('name', 'id'), $user->branch_id, url('get_store'), 'staer_store_id', 'id'],
                ['select', 'staer_store_id', '选择发货门店*', '', StoreModel::where(['status' => 1, 'branch_id' => $user->branch_id])->column('name', 'id'), $user->store_id],
                ['text', 'start_money', '货款*', ''],
                ['text', 'sum', '货物数量*',],
                ['select', 'start_detailed', '货物名称*', '', GoodsModel::where(['status' => 1])->column('name', 'id'), '', 'multiple'],
                ['select', 'receive_id', '选择收货人*', '', CompanyuserModel::column('name', 'id')],
                ['linkage', 'receive_branch_id', '选择收货网点*', '', BranchModel::where(['status' => 1])->column('name', 'id'), '', url('get_store'), 'receive_store_id', 'id'],
                ['select', 'receive_store_id', '选择收货门店*'],
                ['text', 'receive_money', '运费',],
                ['text', 'poundage', '手续费',],
                ['textarea', 'content', '备注',],
            ])
            ->layout([
                'staer_branch_id' => 6, 'staer_store_id' => 6,
                'start_money' => 6, 'start_weight' => 6,
                'companyuser_id' => 12, 'user_id' => 6,
                'receive_branch_id' => 6, 'receive_store_id' => 6,
                'receive_money' => 6, 'poundage' => 6

            ])
            ->fetch();
    }


    /**
     * 根据网点获取门店
     * @author 
     */
    public function get_store()
    {
        $id = input('post.id');
        $data = collection(StoreModel::where(['branch_id' => $id, 'status' => 1])->field('id,name')->select())->toArray();
        if ($data) {
            $arr['code'] = 1; //判断状态
            $arr['msg'] = '请求成功'; //回传信息
            foreach ($data as $key => $value) {
                $list[] = [
                    'key' => $value['id'],
                    'value' => $value['name']
                ];
            }
            $arr['list'] = $list;
        } else {
            $arr['code'] = 0; //判断状态
            $arr['msg'] = '该网点还未有门店'; //回传信息
        }
        return json($arr);
    }


    /**
     * 编辑运单
     * @author 
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        if ($this->request->isPost()) {
            $data = input();
            $validate = $this->validate($data, 'Order');
            if ($validate !== true) $this->error($validate);
            if ($b = OrderModel::update($data)) {
                $this->success('编辑成功', url('index'), '_parent_reload');
            } else {
                $this->error('操作失败', url('index'), '_parent_reload');
            }
        }

        $info = OrderModel::where('id', $id)->find();

        return ZBuilder::make('form')
            ->setPageTitle('编辑托运单')// 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['select', 'start_id', '选择发货人', '', CompanyuserModel::column('name', 'id')],
                //['select', 'user_id', '请选择跟车员','',UserModel::where(['status'=>1,'store_id'=>$info->staer_store_id])->whereor('state','=','1,2')->column('name','id')],
                ['linkage', 'staer_branch_id', '选择发货网点', '', BranchModel::where(['status' => 1])->column('name', 'id'), $info->staer_branch_id, url('get_store'), 'staer_store_id', 'id'],
                ['select', 'staer_store_id', '选择发货门店', '', StoreModel::where(['status' => 1, 'branch_id' => $info->staer_branch_id])->column('name', 'id'), $info->staer_store_id],
                ['text', 'start_money', '货款', ''],
                ['text', 'sum', '货物数量',],
                ['select', 'start_detailed', '货物名称*', '', GoodsModel::where(['status' => 1])->column('name', 'id'), '', 'multiple'],
                ['select', 'receive_id', '选择收货人*', '', CompanyuserModel::column('name', 'id')],
                ['linkage', 'receive_branch_id', '选择收货网点', '', BranchModel::where(['status' => 1])->column('name', 'id'), $info->receive_branch_id, url('get_store'), 'receive_store_id', 'id'],
                ['select', 'receive_store_id', '选择收货门店', '', StoreModel::where(['status' => 1, 'branch_id' => $info->receive_branch_id])->column('name', 'id'), $info->receive_store_id],
                ['text', 'receive_money', '运费',],
                ['text', 'poundage', '手续费',],
                ['textarea', 'content', '备注',],
            ])
            ->setFormData($info)// 设置表单数据
            ->layout([
                'staer_branch_id' => 6, 'staer_store_id' => 6,
                'start_money' => 6, 'start_weight' => 6,
                'companyuser_id' => 12, 'user_id' => 6,
                'receive_branch_id' => 6, 'receive_store_id' => 6,
                'receive_money' => 6, 'poundage' => 6

            ])
            ->fetch();
    }


    public function shouhuo()
    {
        $data = array(
            array(NULL, 2010, 2011, 2012),
            array('Q1', 12, 15, 21),
            array('Q2', 56, 73, 86),
            array('Q3', 52, 61, 69),
            array('Q4', 30, 32, 0),
        );
        $this->create_xls1($data);

    }


    public function qianshou($data = null)
    {
        $data = input();
        dump($data);
    }


    function create_xls1($data, $filename = 'simple.xls')
    {
        ini_set('max_execution_time', '0');
        require_once $_SERVER['CONTEXT_DOCUMENT_ROOT'] . '/application/logistics/vendor/phpexcel/PHPExcel.php';
        $phpexcel = new \PHPExcel();

        $filename = str_replace('.xls', '', $filename) . '.xls';
        $phpexcel->getProperties()
            ->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $phpexcel->getActiveSheet()->fromArray($data);
        $phpexcel->getActiveSheet()->setTitle('Sheet1');
        $phpexcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=$filename");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $objwriter->save('php://output');
        exit;
    }


    /**
     * 删除韵运单
     * @author 
     */
    public function delete($ids = null)
    {
        if ($ids === null) $this->error('缺少参数');
        if (is_array($ids)) {
            foreach ($ids as $k => $v) {
                OrderModel::destroy($v);
            }
        } else {
            OrderModel::destroy($ids);
        }
        $this->success('删除成功');
    }


}